package com.zhijian.warehouse.manage.util;


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class QRCodeGenerator {
    public static String generateQRCode(String content) throws WriterException, IOException {
        // 设置二维码参数
        int width = 500;
        int height = 500;
        String imageFormat = "jpg"; // 输出图像格式
        Map<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定字符集

        // 生成二维码矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);

        // 将二维码矩阵转换为图像输出流
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, imageFormat, outputStream);

        // 将输出流中的图像转换为Base64字符串
        byte[] data = outputStream.toByteArray();
        return java.util.Base64.getEncoder().encodeToString(data);
    }

}
